import { createStore, Store, useStore as useVuexStore } from 'vuex'

import { getPageListData } from '@/service/main/system/system'

import login from './login/login'
import system from './main/system/system'
import dashboard from './main/analysis/dashboard'

import { IRootState } from './types'
import type { IStoreType } from './types'

const store = createStore<IRootState>({
  state: () => {
    return {
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  actions: {
    async getInitialDataAction(context) {
      //请求部门角色数据
      const departmentRes = await getPageListData('/department/list', {
        offset: 0,
        size: 1000
      })
      const RoleRes = await getPageListData('/role/list', {
        offset: 0,
        size: 1000
      })
      const menuRes = await getPageListData('/menu/list', {})

      //保存数据
      context.commit(`changeEntireMenu`, menuRes.data.list)
      context.commit(`changeEntireDepartment`, departmentRes.data.list)
      context.commit(`changeEntireRole`, RoleRes.data.list)
    }
  },
  mutations: {
    changeEntireDepartment(state, payload: any[]) {
      state.entireDepartment = payload
    },
    changeEntireRole(state, payload: any[]) {
      state.entireRole = payload
    },
    changeEntireMenu(state, payload: any[]) {
      state.entireMenu = payload
    }
  },
  //调用模块action要使用此名字
  modules: {
    login,
    system,
    dashboard
  }
})

export function setupStore() {
  store.dispatch('login/loadLocalLogin')
  //直接调用异步可能无法及时拿到token 需要到login和刷新时候去操作
  // store.dispatch('getInitialDataAction')
}
export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
